﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Xml.Linq;
using System.IO;
using System.Xml;
using System.Net;

namespace SAE_Storage_Admin
{
    public partial class Main : Form
    {
        private static string CONFIGFILE = "config.xml";
        private String m_strDomain = "";
        private String m_strUrl = "";
        private ArrayList FileNameList = new ArrayList();

        private  DataSet ds = new DataSet("filelistset");

        public Main()
        {
            InitializeComponent();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            AccessRequest(0);
            // 用于修改list view的单项颜色
            lv_info.GridLines = true; //显示各个记录的分隔线 
            lv_info.FullRowSelect = true; //要选择就是一行 
            lv_info.View = View.Details; //定义列表显示的方式 
            lv_info.Scrollable = true; //需要时候显示滚动条 
            lv_info.MultiSelect = false; // 不可以多行选择 
            lv_info.HeaderStyle = ColumnHeaderStyle.Nonclickable;
            lv_info.Columns.Add("信息", 740, HorizontalAlignment.Left);

            ReadConfig();

            QueryFile(m_strUrl, m_strDomain, dgv_filelist);
        }

        private void btn_query_Click(object sender, EventArgs e)
        {
            if (m_strDomain.Length <= 0 || m_strUrl.Length <= 0)
            {
                ListBoxAddError("URL or DOMAIN is empty, please config first.");
            }
            else
            {
                QueryFile(m_strUrl, m_strDomain, dgv_filelist);
            }
        }

        private void btn_addFile_Click(object sender, EventArgs e)
        {
            //在文件对话框中选择多个文件
            OpenFileDialog MyDlg = new OpenFileDialog();
            MyDlg.Filter = "压缩文件(*.zip)|*.zip|所有文件(*.*)|*.*";
            MyDlg.Title = "选择要上传的文件 *可多选* 按Ctrl键多选";
            MyDlg.Multiselect = true;
            // String MyInfo = "选择的多个文件分别是：";
            if (MyDlg.ShowDialog() == DialogResult.OK)
            {
                ListBoxAddInfo("Add file:");
                FileNameList.Clear();
                foreach (string MyFileName in MyDlg.FileNames)
                {
                    FileNameList.Add(MyFileName);
                    // listbox_info.Items.Add(MyFileName);
                    ListBoxAddInfo(MyFileName);
                    // MyInfo += "\n" + MyFileName;
                }
                // 
                Upload_File();
                // Help.Enabled = true;
                // MessageBox.Show(MyInfo, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void Upload_File()
        {
            ListBoxAddInfo("Start uploading...");
            //  判断配置文件domain和url是否都存在
            if (m_strDomain.Length <= 0 || m_strUrl.Length <= 0)
            {
                // listbox_info.Items.Add("Upload error: domain and url can not be empty");
                ListBoxAddError("Upload error: domain and url can not be empty");
                return;
            }
            // Help.Enabled = false;
            String saveFileName;
            foreach (String i in FileNameList)
            {
                // 去除i中的文件名
                saveFileName = i.Substring(i.LastIndexOf("\\") + 1);
                // lb_info.Text = saveFileName;
                // progressBar.Show();
                int ret = Upload_Request(m_strUrl, m_strDomain, i, saveFileName, progressBar);
                // progressBar.Hide();
                if (ret <= 0)
                {
                    ListBoxAddError("Upload error");
                    MessageBox.Show("上传失败，请重试！");
                }
                // MessageBox.Show(ret.ToString());
            }
        }

        private void btn_settings_Click(object sender, EventArgs e)
        {
            Settings settingsForm = new Settings(this, m_strDomain, m_strUrl);
            settingsForm.ShowDialog();
        }

        private void btn_about_Click(object sender, EventArgs e)
        {
            SSAAboutBox aboutbox = new SSAAboutBox();
            aboutbox.ShowDialog();
        }

        //add info
        public void ListBoxAddInfo(String str)
        {
            ListViewItem item = new ListViewItem(str, 0);
            item.UseItemStyleForSubItems = false;
            item.Text = str;
            item.ForeColor = Color.Black;
            lv_info.Items.Add(item);
            lv_info.Items[lv_info.Items.Count - 1].EnsureVisible();
        }
        // add warning
        public void ListBoxAddWarning(String str)
        {
            ListViewItem item = new ListViewItem(str, 0);
            item.UseItemStyleForSubItems = false;
            item.Text = str;
            item.ForeColor = Color.Yellow;
            lv_info.Items.Add(item);
            lv_info.Items[lv_info.Items.Count - 1].EnsureVisible();
        }
        // add error
        public void ListBoxAddError(String str)
        {
            ListViewItem item = new ListViewItem(str, 0);
            item.UseItemStyleForSubItems = false;
            item.Text = str;
            item.ForeColor = Color.Red;
            lv_info.Items.Add(item);
            // this.lv_info.items[this.lv_info.items.count - 1].ensurevisible();
            lv_info.Items[lv_info.Items.Count - 1].EnsureVisible();
        }

        // 
        private void ReadConfig()
        {
            ListBoxAddInfo("Load config file...");
            String strTemp = "";
            m_strDomain = getXmlValue(CONFIGFILE, "domain", "name");
            strTemp = "domain: " + m_strDomain;
            // listbox_info.Items.Add(strTemp);
            ListBoxAddInfo(strTemp);
            m_strUrl = getXmlValue(CONFIGFILE, "url", "value");
            strTemp = "url: " + m_strUrl;
            // listbox_info.Items.Add(strTemp);
            ListBoxAddInfo(strTemp);
            if ( m_strDomain.Length <= 0 || m_strUrl.Length <= 0 )
            {
                ListBoxAddError("Please config first.");
            }
        }

        /// <summary>   
        /// 返回XMl文件指定元素的指定属性值  
        /// </summary>  
        /// <param name="xmlName">XML文件名</param>
        /// <param name="xmlElement">指定元素</param>  
        /// <param name="xmlAttribute">指定属性</param>  
        /// <returns></returns>  
        public string getXmlValue(string xmlName, string xmlElement, string xmlAttribute)
        {
            string s = "";
            try
            {
                XDocument xmlDoc = XDocument.Load(xmlName);
                var results = from c in xmlDoc.Descendants(xmlElement)
                              select c;
                foreach (var result in results)
                {
                    s = result.Attribute(xmlAttribute).Value.ToString();
                }
            }
            catch (FileNotFoundException)
            {
                // listbox_info.Items.Add("No config file, create one.");
                ListBoxAddWarning("No config file, create one.");
                XmlDocument doc = new XmlDocument();
                doc.LoadXml("<SAEStorage>" +
                                        "<domain name=''></domain>" +
                                        "<url value=''></url>" +
                                    "</SAEStorage>");
                doc.Save(CONFIGFILE);
                // ListBoxAddError("Please config first.");
            }
            return s;
        }

        /// <summary>   
        /// 设置XMl文件指定元素的指定属性的值  
        /// </summary>  
        /// <param name="xmlName">XML文件名</param>
        /// <param name="xmlElement">指定元素</param>
        /// <param name="xmlAttribute">指定属性</param>   
        /// <param name="xmlValue">指定值</param>   
        public void setXmlValue(string xmlName, string xmlElement, string xmlAttribute, string xmlValue)
        {
            XDocument xmlDoc = XDocument.Load(xmlName);
            xmlDoc.Element("SAEStorage").Element(xmlElement).Attribute(xmlAttribute).SetValue(xmlValue);
            xmlDoc.Save(xmlName);
        }

        public void SaveSettings(String domain, String url)
        {
            m_strDomain = domain;
            m_strUrl = url;
            // listbox_info.Items.Add("Save Settings:");
            ListBoxAddInfo("Save Settings:");
            String strTemp = "";
            setXmlValue(CONFIGFILE, "domain", "name", m_strDomain);
            setXmlValue(CONFIGFILE, "url", "value", m_strUrl);
            strTemp = "domain: " + m_strDomain;
            // listbox_info.Items.Add(strTemp);
            ListBoxAddInfo(strTemp);
            strTemp = "upload url: " + m_strUrl;
            // listbox_info.Items.Add(strTemp);
            ListBoxAddInfo(strTemp);
        }

        public void setDomain(String domain)
        {
            m_strDomain = domain;
        }

        public void setUrl(String url)
        {
            m_strUrl = url;
        }

        public String getDomain()
        {
            return m_strDomain;
        }

        public String getUrl()
        {
            return m_strUrl;
        }

        /// <summary>   
        /// 上传文件并在修改进度条显示
        /// </summary>  
        /// <param name="address">网络地址</param>  
        /// <param name="domain">storage域</param>  
        /// <param name="fileNamePath">要上传的文件路径</param>
        /// <param name="saveName">在服务器上保存的名称</param>  
        /// <param name="progressBar">进度条</param>  
        /// <returns></returns>  
        private int Upload_Request(string address, string domain, string fileNamePath, string saveName, ProgressBar progressBar)
        {
            progressBar.Show();
            int returnValue = 0;
            // 要上传的文件 
            FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
            BinaryReader r = new BinaryReader(fs);
            //时间戳 
            // string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
            string strBoundary = "-------------------------7d33a816d302b6";
            byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n");
            //请求头部信息 
            StringBuilder sb = new StringBuilder();
            // operation type
            sb.Append("--");
            sb.Append(strBoundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"");
            sb.Append("op");
            sb.Append("\"\r\n\r\n");
            sb.Append("ADDFILE");
            sb.Append("\r\n");
            // save name
            sb.Append("--");
            sb.Append(strBoundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"");
            sb.Append("fileName");
            sb.Append("\"\r\n\r\n");
            sb.Append(saveName);
            sb.Append("\r\n");
            // domain
            sb.Append("--");
            sb.Append(strBoundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"");
            sb.Append("domain");
            sb.Append("\"\r\n\r\n");
            sb.Append(domain);
            sb.Append("\r\n");
            //
            sb.Append("--");
            sb.Append(strBoundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"");
            sb.Append("file");
            sb.Append("\"; filename=\"");
            sb.Append(saveName);
            sb.Append("\"");
            sb.Append("\r\n");
            sb.Append("Content-Type: ");
            sb.Append("application/octet-stream");
            sb.Append("\r\n");
            sb.Append("\r\n");
            string strPostHeader = sb.ToString();
            // MessageBox.Show(strPostHeader);
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);
            // 根据uri创建HttpWebRequest对象 
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(address));
            httpReq.Method = "POST";
            //对发送的数据不使用缓存 
            httpReq.AllowWriteStreamBuffering = false;
            //设置获得响应的超时时间（300秒） 
            httpReq.Timeout = 300000;
            httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;
            long length = fs.Length + postHeaderBytes.Length + boundaryBytes.Length;
            long fileLength = fs.Length;
            httpReq.ContentLength = length;
            try
            {
                progressBar.Maximum = int.MaxValue;
                progressBar.Minimum = 0;
                progressBar.Value = 0;
                //每次上传4k 
                int bufferLength = 4096;
                byte[] buffer = new byte[bufferLength];
                //已上传的字节数 
                long offset = 0;
                //开始上传时间 
                DateTime startTime = DateTime.Now;
                int size = r.Read(buffer, 0, bufferLength);
                Stream postStream = httpReq.GetRequestStream();
                //发送请求头部消息 
                postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                // 
                String strTime = "";
                String strSize = "";
                while (size > 0)
                {
                    postStream.Write(buffer, 0, size);
                    offset += size;
                    progressBar.Value = (int)(offset * (int.MaxValue / length));
                    TimeSpan span = DateTime.Now - startTime;
                    double second = span.TotalSeconds;
                    // lblTime.Text = "已用时：" + second.ToString("F2") + "秒";
                    strTime = "用时：" + second.ToString("F2") + "秒";
                    if (second > 0.001)
                    {
                        // lblSpeed.Text = " 平均速度：" + (offset / 1024 / second).ToString("0.00") + "KB/秒";
                        // strSpeed = " 平均速度：" + (offset / 1024 / second).ToString("0.00") + "KB/秒";
                    }
                    else
                    {
                        // lblSpeed.Text = " 正在连接…";
                        // strSpeed =  " 正在连接…";
                    }
                    // lblState.Text = "已上传：" + (offset * 100.0 / length).ToString("F2") + "%";
                    // strUploaded = "已上传：" + (offset * 100.0 / length).ToString("F2") + "%";
                    // lblSize.Text = (offset / 1048576.0).ToString("F2") + "M/" + (fileLength / 1048576.0).ToString("F2") + "M";
                    strSize = "文件大小：" + (fileLength / 1048576.0).ToString("F2") + "M";
                    Application.DoEvents();
                    size = r.Read(buffer, 0, bufferLength);
                }
                ListBoxAddInfo(strTime);
                ListBoxAddInfo(strSize);
                // ClearInfoLable();
                //添加尾部的时间戳 
                postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                postStream.Close();
                //获取服务器端的响应 
                WebResponse webRespon = httpReq.GetResponse();
                Stream s = webRespon.GetResponseStream();
                StreamReader sr = new StreamReader(s);
                //读取服务器端返回的消息 
                String sReturnString = sr.ReadLine();
                s.Close();
                sr.Close();
                Boolean flag = false;
                if (sReturnString.ToUpper().IndexOf("SUCCESS") != -1)
                {
                    flag = true;
                    returnValue = 1;
                }
                else if (sReturnString.ToUpper().IndexOf("ERROR") != -1)
                {
                    flag = false;
                    returnValue = 0;
                }
                if ( !flag )
                {
                    returnValue = 0;
                }else{
                    QueryFile(m_strUrl, m_strDomain, dgv_filelist);
                }
            }
            catch (WebException e)
            {
                ListBoxAddError(e.ToString());
                returnValue = 0;
            }
            catch (IOException e)
            {
                ListBoxAddError(e.ToString());
                returnValue = 0;
            }
            catch
            {
                returnValue = 0;
            }
            finally
            {
                progressBar.Hide();
                fs.Close();
                r.Close();
            }
            return returnValue;
        }

        private void QueryFile(String storageUrl, String domain, DataGridView dgv )
        {
            // DataSet ds = new DataSet("filelistset");
            if (m_strDomain.Length <= 0 || m_strUrl.Length <= 0)
            {
                ListBoxAddError("URL or DOMAIN is empty, please config first.");
                return;
            }

            DataTable dt = new DataTable("FileList");
            // dt.Columns.Add(new DataColumn("选择", typeof(Button)));
            dt.Columns.Add(new DataColumn("文件名", typeof(string)));
            dt.Columns.Add(new DataColumn("大小(单位: KB)", typeof(float)));
            dt.Columns.Add(new DataColumn("时间", typeof(string)));
            dt.Columns.Add(new DataColumn("下载路径", typeof(string)));

            try
            {
                string queryUrl = storageUrl + "?domain=" + domain + "&op=QUERYFILELIST";

                ListBoxAddInfo("Query: " + queryUrl);

                XElement doc = XElement.Load(queryUrl);
                var node = from n in doc.Elements("file") select n;
                // var node = from n in doc.Elements("filelist");

                foreach (var xnode in node)
                {
                    string fileName = "";
                    float fileSize = 0.0f;
                    string fileTime = "";
                    string url = "";

                    DataRow row = dt.NewRow();

                    fileName = xnode.Attribute("fileName").Value;
                    fileSize = Convert.ToUInt64(xnode.Attribute("length").Value) / 1024.0f;
                    fileTime = xnode.Attribute("datetime").Value;
                    url = xnode.Attribute("url").Value;

                    // DateTimeFormatInfo dtFI = new DateTimeFormatInfo();
                    // dtFI.ShortDatePattern = "yy/MM/dd/";
                    // DateTime fTime = Convert.ToDateTime(fileTime); 

                    // 读取节点数据 并填充数据行
                    // row["FileName"] = new CheckBox();
                    // row["选择"] = dcButton;
                    row["文件名"] = fileName;
                    row["大小(单位: KB)"] = fileSize.ToString();
                    row["时间"] = getFileTime(long.Parse(fileTime));
                    row["下载路径"] = url;
                    dt.Rows.Add(row);
                }
                // DataSet ds = new DataSet("filelist");
                ds.Tables.Clear();
                ds.Tables.Add(dt);

                DGVBingingData(dgv, ds);

                ListBoxAddInfo("Query OK.");
            }
            catch (System.Exception ex)
            {
                ListBoxAddError(ex.ToString());
            }
        }

        private void DGVBingingData(DataGridView dgv, DataSet ds)
        {
            if (dgv.ColumnCount > 4)
            {
                dgv.Columns.Remove(dgv.Columns[5]);
                dgv.Columns.Remove(dgv.Columns[4]);
                // dgv.Columns.Remove(dgv.ColumnCount);
            }
            
            dgv.DataSource = ds.Tables[0];

            // MessageBox.Show(dgv.Width.ToString());

            dgv.Columns[0].Width = Convert.ToInt32(0.13 * dgv.Width);
            dgv.Columns[1].Width = Convert.ToInt32(0.15 * dgv.Width);
            dgv.Columns[2].Width = Convert.ToInt32(0.18 * dgv.Width);
            dgv.Columns[3].Width = Convert.ToInt32(0.54 * dgv.Width - 203);

           if (dgv.ColumnCount < 5)
            {
                DataGridViewButtonColumn columnDownload = new DataGridViewButtonColumn();
                // 设定列名
                columnDownload.Name = "下载";
                columnDownload.UseColumnTextForButtonValue = true;
                columnDownload.Text = "下载";
                columnDownload.Width = 80;
                // columnDownload.
                dgv.Columns.Add(columnDownload);

                DataGridViewButtonColumn columnDel = new DataGridViewButtonColumn();
                // 设定列名
                columnDel.Name = "删除";
                columnDel.UseColumnTextForButtonValue = true;
                columnDel.Text = "删除";
                columnDel.Width = 80;
                dgv.Columns.Add(columnDel);
            }
        }

        private String getFileTime(long fileTime)
        {
            int offset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Hours;
            DateTime timeStamp = new DateTime(1970, 1, 1);
            long t = (fileTime + offset * 60 * 60) * 10000000 + timeStamp.Ticks;
            DateTime dt = new DateTime(t);
            String strTime = dt.ToString("yyyy-MM-dd HH:mm:ss");
            return strTime;
        }

        private void dgv_filelist_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if ( dgv_filelist.Columns[e.ColumnIndex] is DataGridViewButtonColumn)
            {
                // MessageBox.Show(dgv_filelist.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
                if (dgv_filelist.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "下载")
                {
                    String storageUrl = dgv_filelist.Rows[e.RowIndex].Cells["下载路径"].Value.ToString();
                    String fileName = dgv_filelist.Rows[e.RowIndex].Cells["文件名"].Value.ToString();
                    String saveName = fileName.Substring( fileName.LastIndexOf("/") +1);
                    
                     //在文件对话框中选择一个文件名来保存
                    SaveFileDialog MyDlg = new SaveFileDialog();
                    MyDlg.Filter = "压缩文件(*.zip)|*.zip|所有文件(*.*)|*.*";
                    MyDlg.Title = "输入保存文件名";
                    MyDlg.FileName = saveName;
                    if (MyDlg.ShowDialog() == DialogResult.OK)
                    {
                        saveName = MyDlg.FileName;
                        DownloadFile(storageUrl, saveName, progressBar);
                        ListBoxAddInfo("Download over.");
                        // MessageBox.Show(saveName);
                    }
                }else if (dgv_filelist.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() == "删除")
                {
                    String storageUrl = dgv_filelist.Rows[e.RowIndex].Cells["下载路径"].Value.ToString();
                    String fileName = dgv_filelist.Rows[e.RowIndex].Cells["文件名"].Value.ToString();
                    MessageBoxButtons   buttons   =   MessageBoxButtons.YesNo;
                    if (MessageBox.Show("确认删除？", "请确认", buttons) == DialogResult.Yes)
                    {
                        DeleteFile(m_strUrl, m_strDomain, fileName);
                    }              
                }
            }
        }

        private void dgv_filelist_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgv_filelist.Columns[e.ColumnIndex] is DataGridViewTextBoxColumn)
            {
                // String s = e.ColumnIndex.ToString();
                if (e.ColumnIndex==3)
                {
                    // MessageBox.Show("asdfadsf");
                    String str = dgv_filelist.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                    Clipboard.SetDataObject(str);
                    ListBoxAddInfo("Copy to clipboard.");
                }
            }
        }

        public void DeleteFile(string url, string domain, string filename)
        {
            string requestUrl = url + "?domain=" + domain + "&fileName=" + filename + "&op=DELFILE";
            try
            {
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
                req.Method = "GET"; 
                using (WebResponse wrs = req.GetResponse())
                {
                    //在这里对接收到的页面内容进行处理
                    Stream strm = wrs.GetResponseStream();
                    StreamReader sr = new StreamReader(strm); 
                    string line;
                    Boolean flag = false;
                    while ((line = sr.ReadLine()) != null)
                    {
                        if ( line.ToUpper().IndexOf("SUCCESS") != -1 )
                        {
                            ListBoxAddInfo(line);
                            ListBoxAddInfo("Delete File OK!");
                            flag = true;
                            QueryFile(m_strUrl, m_strDomain, dgv_filelist);
                            break;
                        }
                        if (line.ToUpper().IndexOf("ERROR") != -1)
                        {
                            ListBoxAddError(line);
                            ListBoxAddError("Delete File ERROR!");
                            flag = false;
                            break;
                        }
                    }
                    if ( !flag )
                    {
                        ListBoxAddError("Delete File ERROR!");
                    }
                }  
            }
            catch (System.Exception ex)
            {
                ListBoxAddError("删除文件失败.");
                ListBoxAddError(ex.ToString());
            }
           
        }

        /// <summary>        
        /// 文件下载        
        /// </summary>        
        /// <param name="URL">下载文件地址</param>       
        /// <param name="Filename">下载后的存放地址</param>        
        /// <param name="Prog">用于显示的进度条</param> 
        public void DownloadFile(string URL, string filename, ProgressBar prog)
        {
            float percent = 0;

            ListBoxAddInfo("Download file...");
            prog.Show();
            try
            {
                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;
                if (prog != null)
                {
                    prog.Maximum = (int)totalBytes;
                }
                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                long totalDownloadedByte = 0;
                byte[] by = new byte[4096];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);
                    if (prog != null)
                    {
                        prog.Value = (int)totalDownloadedByte;
                    }
                    osize = st.Read(by, 0, (int)by.Length);
                    percent = (float)totalDownloadedByte / (float)totalBytes * 100;
                }
                so.Close();
                st.Close();
            }
            catch (System.Exception e)
            {
                ListBoxAddError(e.ToString());
                throw;
            }finally{
                prog.Hide();
            }
        }

        private void Help_Click(object sender, EventArgs e)
        {
            // http://ssadmin.sinaapp.com/index.php/help.html
            System.Diagnostics.Process.Start("http://ssadmin.sinaapp.com/index.php/help.html");
        }

        private void Main_KeyDown(object sender, KeyEventArgs e)
        {
            // MessageBox.Show("asdf");
            switch (e.KeyCode)
            {
                case Keys.F1:
                    Help_Click(this, EventArgs.Empty);//这里跟的是你的菜单事件名称
                    break;
            }
        }

        private void dgv_filelist_Resize(object sender, EventArgs e)
        {
            DGVBingingData(this.dgv_filelist, this.ds);
        }

        private void AccessRequest(int flag)
        {
            string requestUrl = "http://ssadmin.sinaapp.com/usercounter.php?f=" + flag.ToString();
            try
            {
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
                req.Method = "GET";
                WebResponse wrs = req.GetResponse();
            }
            catch
            {
            }
        }

        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            AccessRequest(1);
        }
    }
}
